import { app, BrowserWindow, ipcMain, dialog, Menu } from 'electron';
import * as path from 'path';
import { CloudUploader } from './services/CloudUploader';
import { ConfigManager } from './services/ConfigManager';
import { FileComparer } from './services/FileComparer';
import * as iconv from 'iconv-lite';

// 在Windows平台设置环境变量以支持UTF-8
if (process.platform === 'win32') {
    // 设置环境变量以支持中文
    process.env.PYTHONIOENCODING = 'utf-8';
    process.env.NODE_OPTIONS = '--max_old_space_size=4096';
    
    // 设置控制台编码为UTF-8
    try {
      const { execSync } = require('child_process');
      // 同步执行chcp命令确保编码设置生效
      execSync('chcp 65001', { stdio: 'pipe' });
      
      // 重新定义console方法以正确处理UTF-8编码
      const originalLog = console.log;
      const originalError = console.error;
      const originalWarn = console.warn;
      
      console.log = (...args) => {
        const message = args.map(arg => 
          typeof arg === 'string' ? Buffer.from(arg, 'utf8').toString('utf8') : arg
        ).join(' ');
        process.stdout.write(message + '\n', 'utf8');
      };
      
      console.error = (...args) => {
        const message = args.map(arg => 
          typeof arg === 'string' ? Buffer.from(arg, 'utf8').toString('utf8') : arg
        ).join(' ');
        process.stderr.write(message + '\n', 'utf8');
      };
      
      console.warn = (...args) => {
        const message = args.map(arg => 
          typeof arg === 'string' ? Buffer.from(arg, 'utf8').toString('utf8') : arg
        ).join(' ');
        process.stdout.write(message + '\n', 'utf8');
      };
      
      console.log('已设置控制台编码为UTF-8');
    } catch (error) {
      console.log('设置控制台编码失败，但不影响程序运行');
    }
  }

class MainApp {
  private mainWindow: BrowserWindow | null = null;
  private cloudUploader: CloudUploader;
  private configManager: ConfigManager;
  private fileComparer: FileComparer;

  constructor() {
    this.cloudUploader = new CloudUploader();
    this.configManager = new ConfigManager();
    this.fileComparer = new FileComparer();
    this.initializeApp();
  }

  private initializeApp(): void {
    app.whenReady().then(() => {
      this.createWindow();
      this.setupIpcHandlers();
    });

    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit();
      }
    });

    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        this.createWindow();
      }
    });
  }

  private createWindow(): void {
    this.mainWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
      },
      title: '资源桶资源上传工具',
      icon: path.join(__dirname, '../assets/icon.png')
    });

    this.mainWindow.loadFile(path.join(__dirname, 'renderer/index.html'));

    // 设置中文菜单栏
    this.createMenu();

    // 开发环境下打开开发者工具
    if (process.env.NODE_ENV === 'development') {
      this.mainWindow.webContents.openDevTools();
    }
  }

  private createMenu(): void {
    const template: any = [
      {
        label: '文件',
        submenu: [
          {
            label: '选择本地目录',
            accelerator: 'CmdOrCtrl+O',
            click: () => {
              this.mainWindow?.webContents.send('menu-select-local-directory');
            }
          },
          {
            label: '设置',
            accelerator: 'CmdOrCtrl+,',
            click: () => {
              this.mainWindow?.webContents.send('menu-open-settings');
            }
          },
          { type: 'separator' },
          {
            label: '退出',
            accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
            click: () => {
              app.quit();
            }
          }
        ]
      },
      {
        label: '操作',
        submenu: [
          {
            label: '比较文件',
            accelerator: 'CmdOrCtrl+R',
            click: () => {
              this.mainWindow?.webContents.send('menu-compare-files');
            }
          },
          {
            label: '开始上传',
            accelerator: 'CmdOrCtrl+U',
            click: () => {
              this.mainWindow?.webContents.send('menu-start-upload');
            }
          },
          {
            label: '停止上传',
            accelerator: 'CmdOrCtrl+S',
            click: () => {
              this.mainWindow?.webContents.send('menu-stop-upload');
            }
          }
        ]
      },
      {
        label: '查看',
        submenu: [
          {
            label: '重新加载',
            accelerator: 'CmdOrCtrl+R',
            click: () => {
              this.mainWindow?.reload();
            }
          },
          {
            label: '强制重新加载',
            accelerator: 'CmdOrCtrl+Shift+R',
            click: () => {
              this.mainWindow?.webContents.reloadIgnoringCache();
            }
          },
          {
            label: '开发者工具',
            accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I',
            click: () => {
              this.mainWindow?.webContents.toggleDevTools();
            }
          },
          { type: 'separator' },
          {
            label: '实际大小',
            accelerator: 'CmdOrCtrl+0',
            click: () => {
              this.mainWindow?.webContents.setZoomLevel(0);
            }
          },
          {
            label: '放大',
            accelerator: 'CmdOrCtrl+Plus',
            click: () => {
              const currentZoom = this.mainWindow?.webContents.getZoomLevel() || 0;
              this.mainWindow?.webContents.setZoomLevel(currentZoom + 0.5);
            }
          },
          {
            label: '缩小',
            accelerator: 'CmdOrCtrl+-',
            click: () => {
              const currentZoom = this.mainWindow?.webContents.getZoomLevel() || 0;
              this.mainWindow?.webContents.setZoomLevel(currentZoom - 0.5);
            }
          },
          { type: 'separator' },
          {
            label: '全屏',
            accelerator: process.platform === 'darwin' ? 'Ctrl+Cmd+F' : 'F11',
            click: () => {
              const isFullScreen = this.mainWindow?.isFullScreen();
              this.mainWindow?.setFullScreen(!isFullScreen);
            }
          }
        ]
      },
      {
        label: '帮助',
        submenu: [
          {
            label: '关于',
            click: () => {
              this.mainWindow?.webContents.send('menu-show-about');
            }
          }
        ]
      }
    ];

    // 在 macOS 上，第一个菜单项通常是应用程序名称
    if (process.platform === 'darwin') {
      template.unshift({
        label: '资源桶上传工具',
        submenu: [
          {
            label: '关于 资源桶上传工具',
            click: () => {
              this.mainWindow?.webContents.send('menu-show-about');
            }
          },
          { type: 'separator' },
          {
              label: '服务',
              submenu: []
            },
          { type: 'separator' },
          {
            label: '隐藏 资源桶上传工具',
            accelerator: 'Command+H',
            click: () => {
              app.hide();
            }
          },
          {
             label: '隐藏其他',
             accelerator: 'Command+Shift+H',
             click: () => {
               // macOS特有功能，在其他平台不可用
               if (process.platform === 'darwin') {
                 (app as any).hideOthersExcept?.(this.mainWindow!);
               }
             }
           },
           {
             label: '显示全部',
             click: () => {
               // macOS特有功能，在其他平台不可用
               if (process.platform === 'darwin') {
                 (app as any).unhide?.();
               }
             }
           },
          { type: 'separator' },
          {
            label: '退出',
            accelerator: 'Command+Q',
            click: () => {
              app.quit();
            }
          }
        ]
      });
    }

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  }

  private setupIpcHandlers(): void {
    // 选择本地资源目录
    ipcMain.handle('select-local-directory', async () => {
      const result = await dialog.showOpenDialog(this.mainWindow!, {
        properties: ['openDirectory']
      });
      return result.filePaths[0] || null;
    });

    // 保存云服务配置
    ipcMain.handle('save-cloud-config', async (event, config) => {
      return await this.configManager.saveConfig(config);
    });

    // 获取云服务配置
    ipcMain.handle('get-cloud-config', async (event, provider) => {
      return await this.configManager.getConfig(provider);
    });

    // 比较文件变更
    ipcMain.handle('compare-files', async (event, localPath, remotePath, provider) => {
      return await this.fileComparer.compareFiles(localPath, remotePath, provider);
    });

    // 开始上传
    ipcMain.handle('start-upload', async (event, uploadConfig) => {
      return await this.cloudUploader.startUpload(uploadConfig, (progress) => {
        this.mainWindow?.webContents.send('upload-progress', progress);
      });
    });

    // 停止上传
    ipcMain.handle('stop-upload', async () => {
      return await this.cloudUploader.stopUpload();
    });

    // 测试云服务连接
    ipcMain.handle('test-cloud-connection', async (event, config) => {
      try {
        const result = await this.cloudUploader.testConnection(config);
        return { success: true, result };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '未知错误';
        return { success: false, error: errorMessage };
      }
    });

    // 保存远程目录历史记录
    ipcMain.handle('save-remote-path-history', async (event, remotePath) => {
      this.configManager.saveRemotePathHistory(remotePath);
      return true;
    });

    // 获取远程目录历史记录
    ipcMain.handle('get-remote-path-history', async () => {
      return this.configManager.getRemotePathHistory();
    });

    // 获取最后一次使用的远程目录
    ipcMain.handle('get-last-remote-path', async () => {
      return this.configManager.getLastRemotePath();
    });

    // 保存本地目录历史记录
    ipcMain.handle('save-local-path-history', async (event, localPath) => {
      this.configManager.saveLocalPathHistory(localPath);
      return true;
    });

    // 获取本地目录历史记录
    ipcMain.handle('get-local-path-history', async () => {
      return this.configManager.getLocalPathHistory();
    });

    // 获取最后一次使用的本地目录
    ipcMain.handle('get-last-local-path', async () => {
      return this.configManager.getLastLocalPath();
    });

    // 多账号配置相关 IPC 处理器
    
    // 保存账号配置
    ipcMain.handle('save-account-config', async (event, { provider, accountId, accountName, config }) => {
      return await this.configManager.saveAccountConfig(provider, accountId, accountName, config);
    });

    // 更新账号配置
    ipcMain.handle('update-account-config', async (event, { provider, accountId, accountName, config }) => {
      return await this.configManager.saveAccountConfig(provider, accountId, accountName, config);
    });

    // 获取账号配置
    ipcMain.handle('get-account-config', async (event, provider, accountId) => {
      return await this.configManager.getAccountConfig(provider, accountId);
    });

    // 获取提供商的所有账号
    ipcMain.handle('get-provider-accounts', async (event, provider) => {
      return await this.configManager.getProviderAccountList(provider);
    });

    // 删除账号
    ipcMain.handle('delete-account', async (event, provider, accountId) => {
      return await this.configManager.deleteAccount(provider, accountId);
    });

    // 设置默认账号
    ipcMain.handle('set-default-account', async (event, provider, accountId) => {
      return await this.configManager.setDefaultAccount(provider, accountId);
    });
  }
}

new MainApp();